/**
 * Created by yk on 2017/9/18.
 */
var time = 1000;
//document.getElementsByTagName('body')[0].style.height = document.documentElement.clientHeight - 169 + 'px';
////console.log(document.documentElement.clientHeight,document.getElementById('footer').style)
function leftTimer(year, month, day, hour, minute, second) {
  var leftTime =
    new Date(year, month - 1, day, hour, minute, second) - new Date(); //计算剩余的毫秒数
  var days = parseInt(leftTime / 1000 / 60 / 60 / 24, 10); //计算剩余的天数
  var hours = parseInt((leftTime / 1000 / 60 / 60) % 24, 10); //计算剩余的小时
  var minutes = parseInt((leftTime / 1000 / 60) % 60, 10); //计算剩余的分钟
  var seconds = parseInt((leftTime / 1000) % 60, 10); //计算剩余的秒数
  days = checkTime(days);
  hours = checkTime(hours);
  minutes = checkTime(minutes);
  seconds = checkTime(seconds);
  //console.log(days + "天" + hours + "小时" + minutes + "分" + seconds + "秒");
}
//定时器
function mtTimeOut() {
  var timer = setTimeout(function () {
    time--;
    if (time > 0) {
      leftTimer(2017, 11, 11, 11, 11, 11);
      clearTimeout(timer);
      timer = null;
      //console.log(time);
      return mtTimeOut();
    }
  }, time);
}
//mtTimeOut();

function checkTime(i) {
  //将0-9的数字前面加上0，例1变为01
  if (i < 10) {
    i = "0" + i;
  }
  return i;
}

var timer = setInterval(function () {
  if (document.getElementById("load_bg_img").complete) {
    $(".loading").fadeOut();
    clearInterval(timer);
    timer = null;
  }
}, 1000);
var page = {
  card_body: ".card-body",
  card_chance: ".card_chance",
  card_chance1: ".card_chance1",
  card_chance2: ".card_chance2",
  card_chance3: ".card_chance3",
  btn_price: "#btn_price",
  btn_medal: "#btn_medal",
  btn_ruler: "#btn_ruler",
  invite_btn: "#invite_btn",
  game_price: "#game_price",
  game_ruler: "#game_ruler",
  game_madel: "#game_madel",
  game_invite: "#game_invite",
  game_result: "#game_result",
  back_main_btn: ".back-main-btn",
  play_invite: ".play-invite",
  btn_close: ".btn-close",
  btn_reload: ".btn-reload",
  btn_play_again: ".play-again",
  times: "#times",
  play_game_times: 0,
  obj: {},
  coupon: null,
  openId: GetRequest().openId,
  host: getServerHost(),
  compareCard: [],
  count: 0,
  youhuiquan: "",
  hasAward: false,
  clickCount: 0,
  prizeName: [
    "",
    "韩巢定制U盘",
    "500M全国流量",
    "100M全国流量"
  ],
  medal_failed: ".medal-failed",
  medal_success: ".medal-success",
  prizeType: [{
      type: 1,
      imgUrl: "./getImg/1.png"
    },
    {
      type: 2,
      imgUrl: "./getImg/2.png"
    },
    {
      type: 3,
      imgUrl: "./getImg/3.png"
    }
  ],
  oldList: "",
  cardGame: {
    imgList: [],
    lessNum: 0,
    oldList: [1, 2, 3],
    newList: [],
    imgShowList: [],
    cardDesk: [],
    init: function () {
      //   this.cardSort(this.imgShowList, this.cardDesk, 0);
      this.cardSort(this.oldList, this.newList, this.lessNum);
      page.oldList = this.oldList;
    },

    //卡片序号
    cardSort: function (oldList, newList, needNum) {
      var context = this;
      if (oldList.length == needNum) {
        //console.table(newList);
        return;
      }
      var index = Math.floor(Math.random() * oldList.length);
      newList.push(oldList[index]);
      oldList.splice(index, 1);
      return context.cardSort(oldList, newList, needNum);
    },
    //添加图片
    createCard: function (ele, imgUrl) {
      if (undefined || imgUrl) {
        var img = new Image();
        img.onload = function () {
          img.onload = null;
          ele.append(img);
        };
        img.src = imgUrl;
      }
    },
    getImgList: function (newList, imgList, imgShowList) {
      for (var i = 0; i < newList.length; i++) {
        imgShowList.push(imgList[newList[i]]);
      }
      //console.log(imgShowList);
      return imgShowList;
    }
  },
  init: function () {
    closeBar('.closePhone', '#phone_panel');
    var context = this;
    this.showPrice();
    this.pageSwap();
    this.sendAddr();
    //领奖
    this.getPrizeFunc();
    $.when(this.checkUserFunc()).done(function (rs) {
      //console.log(rs);
      if (0 == rs.code) {
        var data = rs.data;
        if (data.offline) {
          location.href = "./activeDownline.html";
        }
        page.play_game_times = data.times;
        page.hasAward = data.hasAward;
        page.userPhone = data.phone;
        page.youhuiquan = data.coupon;
        $("#youhuiquan").text(page.youhuiquan);
        $("#times").text(data.times);
        // if (!page.userPhone) {
        //   alert("您还没有绑定手机号，请先绑定手机号");
        //   var cburl = window.location.href;
        //   var encodedCburl = encodeURIComponent(cburl);
        //   var weixinId = "gh_ad35a4a09b60";
        //   var bangdingUrl =
        //     "http://weixin.unisk.cn/weixinVipController.do?bindingMobile&weixinid=" +
        //     weixinId +
        //     "&openid=" +
        //     page.openId +
        //     "&cburl=" +
        //     encodedCburl;
        //   //console.log(bangdingUrl);
        //   window.location.href = bangdingUrl;
        // }
        if (!data.subscribe) {
          $("#wxFollow")
            .removeClass("none")
            .addClass("fadeIn");
        } else {
          //console.log(page.cardGame.newList);
          if (data.prize) {
            $(".price-list li span").text(page.prizeName[data.prize]);
            $(".price-list li a")
              .attr("data-id", data.prize)
              .text("立即前往");
          }
          page.changeCard();
        }
      }
    });
  },
  //判断是否关注绑定
  checkUserFunc: function () {
    var defer = $.Deferred();
    $.ajax({
      type: "get",
      url: page.host + "ruffleCard/getInfo",
      data: {
        openId: page.openId
      },
      success: function (rs) {
        //console.log(rs);
        defer.resolve(rs);
      },
      error: function () {}
    });
    return defer.promise();
  },
  changeCard: function () {
    var context = this;
    var count = 0;
    var imgUrl,
      imgType = "";
    $(context.card_chance).on("click", function (e) {
      e.stopPropagation();
      count++;
      //console.log("clickCount", count);
      //console.log("剩余次数" + context.play_game_times);
      if (!context.play_game_times) {
        $("#overTimes")
          .removeClass("none")
          .addClass("fadeIn");
        return;
      }
      if (count == 1) {
        var index = Math.floor(Math.random() * 3) + 1;
        // testindex
        index = 2;
        page.prizeType.map(function (items) {
          if (index == items.type) {
            var img = $(e.target);
            imgUrl = items.imgUrl;
            imgType = items.type;
            //console.log(items.imgUrl, imgType);
          }
        });
        context.getCard($(this).children("a")[1], imgUrl);
        $(this).addClass("hover");
      } else if (count == 2) {
        //发起请求判断是否中奖
        $(this).attr("data-flag", "1");
        $(context.card_chance).off();
        count = 0;
        //console.log(count);

        //判断中奖
        page.judgePrize(imgType, e.target);
      }
    });
  },
  getCard: function (ele, imgurl) {
    var context = this;
    //console.log("129" + context.count);
    context.cardGame.createCard(ele, imgurl);
    if (context.clickCount != 2) {
      context.count++;
    }
    if ((context.clickCount = 2)) {
      context.count = 0;
    }
  },
  //初始化
  comCard: function (flag) {
    var context = this;
    context.play_game_times--;
    setTimeout(function () {
      flag
        ?
        ($(context.game_result)
          .css("display", "block")
          .addClass("fadeIn"),
          $(context.medal_failed).css("display", "none"),
          $(context.medal_success).css("display", "block")) :
        ($(context.game_result)
          .css("display", "block")
          .addClass("fadeIn"),
          $(context.medal_failed).css("display", "block"),
          $(context.medal_success).css("display", "none"));
      $(context.times).html(context.play_game_times);
      // 初始化
    }, 1500);
  },
  //判断中奖
  judgePrize(type, event) {
    var context = this;
    var imgUrl;
    var badImgUrl;
    var arry = [1, 2, 3];
    arry.splice(type - 1, 1);
    //console.log(arry);
    // badImgUrl = "./getImg/" + arry[Math.floor(Math.random() * 4)] + ".png";
    // if (page.hasAward) {
    //   context.getCard($(event).next(), badImgUrl);
    //   $(event)
    //     .parent()
    //     .addClass("hover");
    //   page.comCard(!page.hasAward);
    //   return;
    // }
    $.ajax({
      type: "post",
      url: page.host + "ruffleCard/getAward",
      data: {
        openId: page.openId,
        prizeType: type
      },
      success: function (rs) {
        if (0 == rs.code) {
          //console.log(type);

          page.prizeType.map(function (items) {
            if (type == items.type) {
              imgUrl = items.imgUrl;
            }
          });
          badImgUrl =
            "./getImg/" + arry[Math.floor(Math.random() * 2)] + ".png";
          //console.log(badImgUrl);

          if (rs.data.win) {
            context.getCard($(event).next(), imgUrl);
            $(".price-list li span").text(page.prizeName[type]);
            $(".price-list li a")
              .attr("data-id", type)
              .text("立即前往");
            $(event)
              .parent()
              .addClass("hover");
            var prizeBackground = [
              "",
              "prize1.png",
              "prize2.png"
            ];
            $(".medal-success").css({
              background: "url('./img/tinified/" + prizeBackground[type] + "') no-repeat",
              backgroundSize: "5.74rem 4.28rem"
            });
          } else {
            context.getCard($(event).next(), badImgUrl);
            $(event)
              .parent()
              .addClass("hover");
          }
          page.comCard(rs.data.win);
        }
        // context.comCard();
      },
      error: function () {}
    });
  },
  //领奖
  getPrizeFunc: function () {
    $("#getMyPrize").on("click", function (e) {
      e.preventDefault();
      var type = $(this).attr("data-id");
      if (4 != type) {
        if (page.hasAward) {
          alert("您已经领过奖品了");
          return;
        }
      }
      //console.log("----", type);
      if (type == 1) {
        $("#addr_panel")
          .removeClass("none")
          .addClass("fadeIn");
      } else if (type == 2 || type == 3) {
        if (type == 2) {
          $('#flowtype').text('500M全国流量');
        } else if (type == 3) {
          $('#flowtype').text('100M全国流量');
        }
        $("#phone_panel")
          .removeClass("none")
          .addClass("fadeIn");
      } else if (type == 4) { //奖品不同类型不同的弹窗
        $("#youhui_panel")
          .removeClass("none")
          .addClass("fadeIn");
        $.ajax({
          type: "post",
          url: page.host + "ruffleCard/receive",
          data: {
            openId: page.openId
          },
          beforeSend: function () {},
          completed: function () {},
          success: function (rs) {
            if (0 == rs.code) {
              page.hasAward = true;
              page.youhuiquan = rs.data.coupon;
              $("#youhuiquan").text(page.youhuiquan);
              location = location;
            }
          },
          error: function () {}
        });
      } else if (type == 5) {
        $.ajax({
          type: "post",
          url: page.host + "ruffleCard/receive",
          data: {
            openId: page.openId
          },
          beforeSend: function () {},
          completed: function () {},
          success: function (rs) {
            if (0 == rs.code) {
              alert("领取成功");
              location = location;
            }
          },
          error: function () {}
        });
      }
    });
  },
  //填地址
  sendAddr: function () {
    //填地址
    $("#sendAddrBtn").on("click", function () {
      if (!$("#uname").val()) {
        alert("请填写姓名");
        return;
      }
      if (!checkMobile($("#uphone").val())) {
        alert("请填写11位手机号");
        return;
      }
      if (!$("#uaddr").val()) {
        alert("请填写地址");
        return;
      }
      $.ajax({
        type: "post",
        url: page.host + "ruffleCard/saveAddress",
        data: {
          openId: page.openId,
          username: $("#uname").val(),
          phone: $("#uphone").val(),
          address: $("#uaddr").val()
        },
        beforeSend: function () {},
        completed: function () {},
        success: function (rs) {
          if (0 == rs.code) {
            alert("领取成功");
            $("#addr_panel").hide();
            location.href = self.location;
          }
        },
        error: function () {}
      });
    });
    //填手机号
    $("#sendphoneBtn").on("click", function () {
      if (!checkMobile($("#flowphone").val())) {
        alert("请填写11位手机号");
        return;
      }
      $.ajax({
        type: "post",
        url: page.host + "ruffleCard/saveAddress",
        data: {
          openId: page.openId,
          username: '',
          phone: $("#flowphone").val(),
          address: ''
        },
        beforeSend: function () {},
        completed: function () {},
        success: function (rs) {
          if (0 == rs.code) {
            alert("领取成功");
            $("#phone_panel").hide();
            location.href = self.location;
          }
        },
        error: function () {}
      });
    });
  },
  showPrice: function () {
    var context = this;
    $(context.btn_price).click(function (e) {
      e.preventDefault();
      MyToggle(context.game_ruler, "[data-toggle='1']", 500);
      page.rulerScroller();
    });
  },
  pageSwap: function () {
    var context = this;
    var clickFlag = 1;
    $(context.back_main_btn).click(function (e) {
      e.preventDefault();
      MyToggle(context.card_body, "[data-toggle='1']", 500);
    });
    $(".closeAddr").click(function (e) {
      e.preventDefault();
      $("#addr_panel")
        .addClass("none")
        .removeClass("fadeIn");
    });
    $(".closeYouhui").click(function (e) {
      e.preventDefault();
      $("#youhui_panel").addClass("none");
    });

    $(context.invite_btn).click(function (e) {
      e.preventDefault();
      //   todo: 弹窗
      $("#share").show();
    });
    $(context.btn_medal).click(function (e) {
      e.preventDefault();
      MyToggle(context.game_price, "[data-toggle='1']", 500);
    });
    $(context.btn_ruler).click(function (e) {
      e.preventDefault();
      MyToggle(context.game_madel, "[data-toggle='1']", 500);
    });
    $(context.btn_close).click(function (e) {
      e.preventDefault();
      var toMian = "#" + $(this).attr("data-close");
      if ("#game_invite" == toMian) {
        $(".header").fadeIn(500);
        $(".footer").fadeIn(500);
      }
      //console.log(toMian);
      //console.log(context.card_body);
      MyToggle(context.card_body, toMian);
    });
    $(context.btn_reload).click(function (e) {
      e.preventDefault();
      MyToggle(context.card_body, context.game_result);
      //todo:查看剩余次数判断是否还有机会
      //console.log("------");
      context.changeCard();
      //console.log("------");
      $(context.card_chance)
        .removeClass("hover")
        .find(".card-face img")
        .remove();
    });
    $(context.play_invite).click(function (e) {
      e.preventDefault();
      context.changeCard();
      $(context.card_chance).removeClass("hover");
      $(context.card_chance)
        .removeClass("hover")
        .find(".card-face img")
        .remove();
    });
    $(context.btn_play_again).click(function (e) {
      e.preventDefault();
      MyToggle(context.card_body, context.game_result);
      //todo:查看剩余次数判断是否还有机会
      //console.log("------");
      context.changeCard();
      //console.log("------");
      $(context.card_chance)
        .removeClass("hover")
        .find(".card-face img")
        .remove();
    });
  },
  rulerScroller: function () {
    var scroll = new iScroll("rulerWrapper", {
      useTransform: false,
      vScroll: true,
      hScroll: false,
      hScrollbar: false,
      checkDOMChanges: true,
      hideScrollbar: true,
      onBeforeScrollStart: function (e) {
        //水平滚动
        var target = e.target;
        while (target.nodeType != 1) target = target.parentNode;
        //在iscroller里经常会有select,input等属性默认不可点击，阻止默认操作就可以点击了
        if (
          target.tagName != "SELECT" &&
          target.tagName != "INPUT" &&
          target.tagName != "TEXTAREA" &&
          target.tagName != "A" &&
          target.tagName != "IMG" &&
          target.tagName != "li"
        )
          e.preventDefault();
      }
    });
  }
};

function MyToggle(showObj, hideObj, time) {
  $(hideObj).fadeOut(0);
  $(showObj).fadeIn(time);
}
page.init();